#include "port.h"
#include  "qkeymetro.h"
#include  <QSharedPointer>
#include  "buffer.h"

Port::Port(bool isOut, int nChannels, QString name) :
         name_(name),isOut_(isOut)
{
    for (int i= 0; i<nChannels; ++i)
        isOut ? buffers_.append(QSharedPointer<Buffer>(new Buffer())) : buffers_.append(QSharedPointer<Buffer>());
}

int Port::getNChannels()
{
    return buffers_.count();
}

bool Port::isOut()
{
    return isOut_;
}

void Port::join(Port & port)
{
    if (this->isOut() == port.isOut()) return; // can't connect out to out or in to in

    int n;
    port.getNChannels() < this->getNChannels() ? n = port.getNChannels() : n = this->getNChannels();
    Port * in = (this->isOut() ? &port : this);
    Port * out = (this->isOut() ? this : &port);
    for(int i = 0; i<n ; ++i)
        in->buffers_[i] = out->buffers_[i];
    return;
}

QSharedPointer <Buffer> & Port::getBuffer(int channelNo)
{

    if (channelNo < 0 || channelNo > getNChannels()) QKeyMetro::StaticData::log(QString("BUF:Bad Buffer Req"));
    return buffers_[channelNo];

}

void Port::setBuffer(QSharedPointer <Buffer> buffer, int channelNo){
    if (channelNo >= 0 && channelNo < getNChannels()) buffers_[channelNo] = buffer;
    return;
};

const QString & Port::getName()
{
    return name_;
}

void Port::setName(QString & name)
{
    name_=name;
    return;
}
